package com.example.controller;
import com.example.entity.Goods;
import com.example.entity.Goodstype;
import com.example.service.impl.GoodsServiceimpl;
import com.example.service.impl.GoodstypeServiceimpl;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Controller
@RequestMapping("/admin")
public class Goodscontroller {
    @Resource
    GoodsServiceimpl goodsService;
    @Resource
    GoodstypeServiceimpl goodstypeService;

    @ApiOperation("获取所有商品")
    @RequestMapping(value = "/goods",method = {RequestMethod.GET,RequestMethod.POST})
    public String findAllGoods(Model model, HttpServletRequest request,
           @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum
         , @RequestParam(value = "pageSize",required = false,defaultValue = "4") Integer pageSize){

        System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝" + pageNum + "============" + pageSize);
        PageInfo<Goods> goodslist = goodsService.queryAll(pageNum,pageSize);
        model.addAttribute("goodsListPage",goodslist);
        String referer = request.getHeader("Referer");
        if (referer.equals("http://localhost:8080/admin/goodsadd")) {
            model.addAttribute("agd","商品信息添加成功！");
        }
        return "goodsList";
    }

    @GetMapping("/delGoods/{id}")
    public String delGoods(@PathVariable("id") int id,Model model){
        int num =goodsService.deleteByID(id);
        model.addAttribute("msg","删除成功");
        return "forward:/admin/goods";
    }

@GetMapping("/Goods/{id}")
public String getGoodsById(@PathVariable("id") int id,Model model){
    Goods goods = goodsService.findById(id);
    ArrayList <Goodstype> list= goodstypeService.queryAll2();
    model.addAttribute("goods",goods);
    model.addAttribute("goodstypesList",list);
    return "goodsEdit";
}

    @PostMapping("/editGoods")
    public String addGoods(Goods goods,Model model){
        System.out.println(goods);
        int num = goodsService.update(goods);
        model.addAttribute("msg","商品信息更新成功！");
        ArrayList<Goodstype> goodstypesList = goodstypeService.queryAll2();
        model.addAttribute("goodstypesList",goodstypesList);
        return "goodsEdit";
    }

    @GetMapping("/goodsadd")
    public  String insertGoods(Goods goods, Model model){
       ArrayList<Goodstype> goodstypesList = goodstypeService.queryAll2();
       model.addAttribute("goodstypesList",goodstypesList);
       return "goodsadd";
    }

    @PostMapping("/goods2")
    public  String addGood(Goods goods,Model model){
        System.out.println(goods);
      int num2 = goodsService.insert(goods);
      return "redirect:/admin/goods";
    }
}
